import { type Ref, ref, computed } from "vue";
import html2pdf from "html2pdf.js";
import { ElMessage, ElLoading } from "element-plus";

interface PdfOptions extends html2pdf.Options {
  margin?: number | number[];
  filename?: string;
  image?: { type: string; quality: number };
  html2canvas?: { scale: number; useCORS: boolean, scrollY: number, logging: boolean, onclone: (clonedDoc: Document) => void };
  jsPDF?: { unit: string; format: number[] ; orientation: string, margin?: number[] };
  pagebreak?: { mode: string[] , before?: string , after?: string, avoid?: string};
  // 新增回调配置
  onBeforeExport?: () => boolean | Promise<boolean>;
  onAfterExport?: () => void;
}

interface UseHtmlToPdfOptions {
  exportTargetRef: Ref<HTMLElement | null>;
  fileName?: string;
  options?: PdfOptions;
  // 新增回调配置
  onBeforeExport?: () => boolean | Promise<boolean>;
  onAfterExport?: () => void;
}

export function useHtmlToPdf(options: UseHtmlToPdfOptions) {
  console.log("useHtmlToPdf options:", options);
  const isExporting = ref(false);
  // 默认配置选项
  const defaultOptions: PdfOptions = {
    margin: 10,
    filename: options.fileName || "导出文件.pdf",
    image: { type: "jpeg", quality: 0.98 },
    html2canvas: {
      scale: 2, // 根据内容密度动态调整
      scrollY: 0,
      useCORS: true,
      logging: true,
      onclone: (clonedDoc) => {
        clonedDoc.body.style.width = '100%';
        clonedDoc.body.style.height = 'auto';
      }
    },
    jsPDF: {
      unit: 'mm',
      format: [297, 210], // A4横向尺寸
      orientation: 'landscape'
    },
    pagebreak: {
      // mode: 'avoid-all',
      mode: ['avoid-all', 'css', 'legacy'], // 避免自动分页
      before: '.page-break-before',
      after: '.page-break-after',
      avoid: '[data-page-break="avoid"]'
    }
  };
  // 导出前预处理 ： 处理图片
  const preprocessContent = (element: HTMLElement) => {
    const cloneEl = element.cloneNode(true) as HTMLElement;
    cloneEl.style.width = '100%';
    cloneEl.querySelectorAll('img').forEach(img => {
      img.style.maxHeight = '200px';
      img.style.objectFit = 'contain';
    });
    return cloneEl;
  }
  const calculateScale = (contentHeight: number) => {
    const maxPageHeight = 1122; // A4纸像素高度
    return Math.min(0.6, maxPageHeight / contentHeight);
  }
  // 合并用户自定义选项
  const mergedOptions = computed(() => ({
    ...defaultOptions,
    ...options.options,
    filename: options.fileName || defaultOptions.filename
  }));

  // 修改handleExport方法，支持动态传入回调参数
  const handleExport = async (dynamicCallbacks?: {
    onBeforeExport?: () => boolean | Promise<boolean>;
    onAfterExport?: () => void;
  }) => {
    if (!options.exportTargetRef.value) {
      ElMessage.error("未找到要导出的内容");
      return;
    }

    // 执行导出前检查（优先使用动态传入的回调）
    const canExport = await (dynamicCallbacks?.onBeforeExport?.() ??
      options.onBeforeExport?.() ??
      Promise.resolve(true));
    // 如果检查不通过，则终止导出流程
    if (!canExport) return;

    isExporting.value = true;
    let loadingInstance;
    try {
      ElMessage.info("正在生成PDF...");
      loadingInstance = ElLoading.service({
        fullscreen: true,
        background: "rgba(110, 110, 110, 0.2)" // 添加背景颜色配置
      });
      await html2pdf()
        .from(options.exportTargetRef.value)
        .set(mergedOptions.value)
        .save();

      loadingInstance.close();
      // ElMessage.success("PDF导出成功");
      isExporting.value = false;
      // 优先调用动态传入的成功回调
      dynamicCallbacks?.onAfterExport?.() ?? options.onAfterExport?.();
    } catch (error) {
      loadingInstance.close();
      isExporting.value = false;
      if (error instanceof Error) {
        if (error.message.includes("html2canvas")) {
          ElMessage.error("画布渲染失败，请检查内容格式");
        } else if (error.message.includes("jsPDF")) {
          ElMessage.error("PDF生成失败，请联系管理员");
        } else {
          ElMessage.error(`导出失败：${error.message}`);
        }
      } else {
        ElMessage.error("发生未知错误，请重试");
      }
    }
  };

  // 保持原有导出格式
  return {
    isExporting,
    handleExport
  };
}
